//
//  GFPhotoBrowearViewCell.swift
//  我的微博练习
//
//  Created by zhangguo on 15/10/23.
//  Copyright © 2015年 zhangguo. All rights reserved.
//

import UIKit
import SDWebImage

//定义协议
protocol PhotoBrowserCellDelegate: NSObjectProtocol {

    //图像视图缩放
    func photoCellDidZoom(scale:CGFloat)
    //完成缩放
    func photoCellDidEndZoom()
}

class PhotoBrowearViewCell: UICollectionViewCell {
    //代理
    weak var photoDelegate: PhotoBrowserCellDelegate?
    
    var imageURLS:  NSURL? {
        didSet {
            //显示菊花
            indicator.startAnimating()
            resetScrollerView ()
            //去除缓存
            imageView.image = nil
            
            //模拟延时
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0)), dispatch_get_main_queue(), { () -> Void in
                
                self.imageView.setImageWithURL(self.imageURLS) { (image, _, _) in
                    
                    self.indicator.stopAnimating()
                    
                    if image == nil {
                        print("下载错误")
                        return
                    }
                    self.setupImagePosion()
                }

            })
        }
        
    }
    
    //重设scrollerView的偏移属性,保证在每次查看新图片时候重新设置，不会cell重用
    private func resetScrollerView () {
        //重设imageView的形变
        imageView.transform = CGAffineTransformIdentity
        
        ScrollView.contentInset = UIEdgeInsetsZero
        ScrollView.contentSize = CGSizeZero
        ScrollView.contentOffset = CGPointZero
        
    }
    
    //设置图片位置
    private func setupImagePosion() {
        let s = self.displaySize(imageView.image!)
        
        self.imageView.frame = CGRect(origin: CGPointZero, size: s)
        //图片垂直居中
        if s.height < ScrollView.bounds.height {
            
            let y = (ScrollView.bounds.height - s.height) * 0.5
            self.imageView.frame = CGRect(origin: CGPointZero, size: s)
            
            //这样设置可以使得图片与上边和下边的间距永远是 y 这么长，而且垂直居中
            ScrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
            
        }else {
            //长图
            self.imageView.frame = CGRect(origin: CGPointZero, size: s)
            ScrollView.contentSize = s
        }
    }

    //长短图实现
    private func displaySize(image:UIImage) -> CGSize {
        //图像的宽高比
        let scale =  image.size.height  / image.size.width
        let height = scale * ScrollView.bounds.width
        
        return CGSize(width: ScrollView.bounds.width, height: height)
    }
    
   override init(frame: CGRect) {
        
        super.init(frame: frame)
        setupUI()
    }
 
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        //添加控件
        contentView.addSubview(ScrollView)
        ScrollView.addSubview(imageView)
        contentView.addSubview(indicator)
        
        //设置布局
        ScrollView.frame = UIScreen.mainScreen().bounds
        indicator.center = ScrollView.center
        
        //设置控件
        prepareScrollView()
        
    }
    //准备scrollView
    private func prepareScrollView() {
        //此处设置缩放的比例
        ScrollView.delegate = self
        ScrollView.maximumZoomScale = 2.0
        ScrollView.minimumZoomScale = 0.5
        
    }

    //懒加载控件
    private lazy var ScrollView = UIScrollView()
     lazy var imageView = UIImageView()
    //下载提示符（菊花）
    private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
   }

extension PhotoBrowearViewCell: UIScrollViewDelegate {
        
        //实现图片缩放唯一的语句是以view开头的语句
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    
    //缩放完成后调用一次
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        
        //重新计算间距,可以在缩放的时候把图片放到屏幕正中间
        var offsetX = (ScrollView.bounds.width - view!.frame.width) * 0.5
        
        //如果offsetx小于0，需要修正边距,让图像距离屏幕边距的距离为0，和屏幕边缘对齐
        offsetX = offsetX < 0 ? 0 : offsetX
        
        var offsetY = (ScrollView.bounds.height - view!.frame.height) * 0.5
        offsetY = offsetY < 0 ? 0 : offsetY
        ScrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
        
        photoDelegate?.photoCellDidEndZoom()
    }
    
    //只要缩放就会调用
    func scrollViewDidZoom(scrollView: UIScrollView) {
        //通知代理，视图的缩放比例
        photoDelegate?.photoCellDidZoom(imageView.transform.a)

    }
}
